package com.lxl.miaosha.controller;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@RestController
public class SendMsgController {

    @Autowired
    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法

    @GetMapping("/sendMsg")
    public String sendDirectMsg() {  //创建200个线程，每个线程模拟1个用户抢单
        for(int i=1;i<=200;i++) {
            final int userId=i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //将消息封装为Map
                    String messageId = String.valueOf(UUID.randomUUID());
                    String messageData = userId+"";
                    String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    Map<String, Object> map = new HashMap<>();
                    map.put("messageId", messageId);
                    map.put("messageData", messageData);
                    map.put("createTime", createTime);
                    //将消息绑定路由键：MyDirectRouting 发送到交换机MyDirectExchange
                    rabbitTemplate.convertAndSend("MiaoshaExchange", "MiaoshaRouting", map);
                }
            }).start();

        }
        return "消息发送成功";
    }


}
